/*
 * @Descripttion: 
 * @version: 0.0.0.1
 * @Author: chenyf15482
 * @Date: 2023-01-29 09:33:08
 * @LastEditors: chenyf15482
 * @LastEditTime: 2023-01-31 16:30:35
 */
import { withModifiers } from 'vue';
import { ElButton, TableColumnCtx, ButtonProps } from 'element-plus'
import { u_formatDateTime } from '@/utils';
import fields from './fields';

interface CustomColumn {
  _type: string,
}

export interface YfLinkBtn extends Partial<ButtonProps> {
  name: string
  width: number,
  onClick: (params: any, some: any) => void
}

interface YfLinkBtnColumn extends CustomColumn {
  _type: 'link',
  props?: Partial<TableColumnCtx<any>>,
  selects: (string | YfLinkBtn)[]
  btns?: Record<string, YfLinkBtn>
}

interface YfDatetimeColumn extends CustomColumn {
  _type: 'datetime',
  props?: Partial<TableColumnCtx<any>>,
  dateKey?: string
  timeKey?: string
}

interface YfKeyColumn extends Partial<TableColumnCtx<any>> {
  key: string,
}

export type YfTableColumn = Partial<TableColumnCtx<any>> | YfLinkBtnColumn | YfDatetimeColumn | YfKeyColumn;

const linkColumn = (column: YfLinkBtnColumn) => {
  let btns: YfLinkBtn[] = [], width = 0;
  column.selects.forEach(item => {
    let btn;
    if (typeof item === 'string') {
      btn = (column.btns || {})[item];
    } else {
      btn = item;
    }
    // todo 如果btns中没有能匹配的，可以控制台报错提示一下？
    if (btn) {
      width = width + btn.width;
      btns.push(btn);
    }
  })
  const render = btns.length > 0 ? (h: any, params: unknown) => {
    const childrens = btns.map(item => {
      const onClick = withModifiers(() => { item.onClick(params, item) }, ['stop']);
      return h(ElButton, { type: 'primary', link: true, ...item, onClick }, { default: () => item.name })
    })
    return h('div', childrens);
  } : undefined;
  return { label: '操作', align: 'center', width: `${width}px`, ...column.props, render }
}

const datetimeColumn = (column: YfDatetimeColumn) => {
  const render = (h: any, params: any) => {
    const title = u_formatDateTime(params.row[column.dateKey || 'occurDate'] + ' ' + params.row[column.timeKey || 'occurTime'])
    return h('div', title);
  }
  return { label: '时间', width: '150px', ...column.props, render };
}

const keyColumn = (column: YfKeyColumn) => {
  return { ...fields[column.key], ...column }
}

const columnMap = new Map<string, any>();
columnMap.set('link', linkColumn)
columnMap.set('datetime', datetimeColumn)
columnMap.set('key', keyColumn)

export const formatTableColumn = (columns: YfTableColumn[]) => {
  const result = columns.map((column, index) => {
    let { _type, key } = column as CustomColumn & YfKeyColumn;
    _type = key ? 'key' : _type;
    if (_type) {
      const fn = columnMap.get(_type);
      const _column = fn ? fn(column) : column;
      return { key: index, ..._column };
    }
    return { key: index, ...column };
  })
  return result;
}